<?php

namespace app\controller;

use app\model\ShopData;
use Carbon\Carbon;
use Dcat\EasyExcel\Excel;
use support\Log;
use support\Request;
use support\Response;

class IndexController
{
    public function push(Request $request): Response
    {
        $price=$request->input('price');
        $title=$request->input('title');
        $salesCount=$request->input('salesCount');
        $comment=$request->input('comment');
        $day=$request->input('day');
        $shop_name=$request->input('shopname');
        $shop=ShopData::where('title',$title)->first();
//        if ($shop && (int)$shop->salesCount === (int)$salesCount){
//            return json(['code'=>200,'msg'=>'success','status'=>true]);
//        }
        $day=Carbon::parse($day)->format('Y-m-d');
        $data=[
            'minprice'=>$price,
            'maxprice'=>$price,
            'title'=>$title,
            'salesCount'=>$salesCount,
            'comment'=>$comment,
            'day'=>$day,
            'shop_name'=>$shop_name,
        ];
        if (isset($price) && str_contains($price,'-')){
            $price=explode('-',$price);
            $data['minprice']=$price[0];
            $data['maxprice']=$price[1];
        }
        Log::info(print_r($data,true));
        ShopData::updateOrCreate($data,['title'=>$title,'shop_name'=>$shop_name,'day'=>$day]);
        return json(['code'=>200,'msg'=>'success','status'=>true]);
    }



    public function export(Request $request)
    {
        $headings = ['id' => 'ID', 'shop_name' => '店铺名称', 'price' => '价格','salesCount'=>'销量','comment'=>'累计评价','day'=>'采集日期'];
        $data = ShopData::all()->toArray();
        $fileName = 'shop_data'.date('YmdHis');
        Excel::export($data)->headings($headings)->store(public_path().'/users.xlsx');
        return response()->download(public_path().'/users.xlsx',$fileName.'.xlsx');
    }

}
